package com.huxiu;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.responses.ProfileResponse;
import com.huxiu.pagers.MyPager;
import com.huxiu.utils.Constants;
import com.huxiu.utils.Global;
import com.huxiu.utils.NetUtil;
import com.huxiu.utils.Settings;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.Map;

public class LogInActivity extends AuthenticatorActivity implements View.OnClickListener {

    @ViewInject(R.id.rg_content_bottom)
    private RadioGroup rg_content_bottom;
    @ViewInject(R.id.login_text_denglu)
    private RadioButton textDenglu;
    @ViewInject(R.id.login_text_zhuce)
    private RadioButton textZhuCe;
    @ViewInject(R.id.disanfang_title)
    private TextView disanfang_title;


    //登录界面
    @ViewInject(R.id.frame_denglu)
    private LinearLayout framedDenglu;
    @ViewInject(R.id.username_edit)
    private EditText usernameEdit;
    @ViewInject(R.id.password_edit)
    private EditText passwordEdit;
    @ViewInject(R.id.log_in_button)
    private Button dengluButton;
    //    @ViewInject(R.id.forget_password)
    //    private TextView forgetPassword;
    @ViewInject(R.id.denglu_qq)
    private ImageView dengluQQ;
    @ViewInject(R.id.denglu_weixin)
    private ImageView dengluWX;
    @ViewInject(R.id.denglu_sina)
    private ImageView dengluSina;

    //注册界面
    @ViewInject(R.id.frame_zhuce)
    private LinearLayout framedZhuCe;

    @ViewInject(R.id.zhuce_shouji)
    private EditText zcShouJi;
    @ViewInject(R.id.zhuce_fasongyanzheng)
    private TextView zcFaSong;
    @ViewInject(R.id.zhuce_yanzhengma_edit)
    private EditText zcYanzhengma;
    @ViewInject(R.id.zhuce_username_edit)
    private EditText zcUsername;
    @ViewInject(R.id.zhuce_password_edit)
    private EditText zcPassword;

    @ViewInject(R.id.img_inputtype)
    private ImageView img_inputtype;
    //    @ViewInject(R.id.zhuce_see_password)
    //    private ImageView seePassword;
    @ViewInject(R.id.zhuce_yonghuxieyi)
    private TextView yonghuxieyi;


    @ViewInject(R.id.zhuce_button)
    private Button zhuceButton;

    @ViewInject(R.id.zhuce_guanlianzhanghao)
    private TextView zhuce_guanlianzhanghao;
    @ViewInject(R.id.zhuce_guanlianzhanghao1)
    private TextView zhuce_guanlianzhanghao1;

    @ViewInject(R.id.login_close)
    private ImageView close;

    private MyPager myPager;
    private String intentStr;
    private String token;
    private String openId;
    private int typeID;

    private LogInActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);
        ViewUtils.inject(this);
        instance=this;
        intentStr = getIntent().getStringExtra("disanfang");
        token = getIntent().getStringExtra("tokenStr");
        openId = getIntent().getStringExtra("openIdStr");
        typeID = getIntent().getIntExtra("type_id", 0);
        if ("sanfangguanlian".equals(intentStr)) {
            rg_content_bottom.setVisibility(View.GONE);
            disanfang_title.setVisibility(View.VISIBLE);
            framedDenglu.setVisibility(View.GONE);
            framedZhuCe.setVisibility(View.VISIBLE);
            zhuce_guanlianzhanghao.setVisibility(View.VISIBLE);
            zhuce_guanlianzhanghao1.setVisibility(View.VISIBLE);
            zhuce_guanlianzhanghao.setOnClickListener(this);
        } else {
            rg_content_bottom.setVisibility(View.VISIBLE);
            disanfang_title.setVisibility(View.GONE);
            framedDenglu.setVisibility(View.VISIBLE);
            framedZhuCe.setVisibility(View.GONE);
            zhuce_guanlianzhanghao.setVisibility(View.GONE);
            zhuce_guanlianzhanghao1.setVisibility(View.GONE);
        }
        dengluButton.setOnClickListener(this);
        dengluQQ.setOnClickListener(this);
        dengluSina.setOnClickListener(this);
        dengluWX.setOnClickListener(this);
        close.setOnClickListener(this);
        img_inputtype.setOnClickListener(this);
        rg_content_bottom.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        zcFaSong.setOnClickListener(this);
        yonghuxieyi.setOnClickListener(this);
        zhuceButton.setOnClickListener(this);
//        if (BuildConfig.DEBUG) {
//            usernameEdit.setText("15611823564");
//            passwordEdit.setText("123456");
//        }
    }

    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.login_text_denglu:
                    framedZhuCe.setVisibility(View.GONE);
                    framedDenglu.setVisibility(View.VISIBLE);
                    break;
                case R.id.login_text_zhuce:
                    framedZhuCe.setVisibility(View.VISIBLE);
                    framedDenglu.setVisibility(View.GONE);
                    break;
            }
        }

    }

    private Intent intent;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.log_in_button:
                if (inputValid()) {
                    if (!NetUtil.checkNet(this)) {
                        Utils.showToast(R.string.generic_check);
                        return;
                    }
                    logIn();
                }
                break;
            case R.id.zhuce_yonghuxieyi:
                intent = new Intent(this, UserXieyiActivity.class);
                startActivity(intent);
                break;
            case R.id.denglu_qq:

                if (!NetUtil.checkNet(this)) {
                    Utils.showToast(R.string.generic_check);
                    return;
                }
                if (mTencent != null) {
                    mTencent.login(this, "all", this);
                } else {
                    Toast.makeText(this, "qq登录失败", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.denglu_sina:
                if (!NetUtil.checkNet(this)) {
                    Utils.showToast(R.string.generic_check);
                    return;
                }
                if (mSsoHandler != null) {
                    mSsoHandler.authorize(this);
                } else {
                    Utils.showToast("新浪登录失败");
                }
                break;
            case R.id.denglu_weixin:
                Constants.WX_TYPE=Constants.WX_LOGIN;
                if (!NetUtil.checkNet(this)) {
                    Utils.showToast(R.string.generic_check);
                    return;
                }
                if (mWechatApi.isWXAppInstalled()) {
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    mWechatApi.sendReq(req);
                } else {
                    Utils.showToast(R.string.weixin_not_installed);
                }
                break;
            case R.id.zhuce_button:
                if (!NetUtil.checkNet(this)) {
                    Utils.showToast(R.string.generic_check);
                    return;
                }
                if (inputZhuCeValid()) {
                    checkUserName();
                }
                break;
            case R.id.zhuce_fasongyanzheng:
                if (!NetUtil.checkNet(this)) {
                    Utils.showToast(R.string.generic_check);
                    return;
                }
                if (TextUtils.isEmpty(zcShouJi.getText().toString())) {
                    Utils.showToast(R.string.pls_input_mobile);
                } else if (zcShouJi.getText().toString().trim().length() != 11) {
                    Utils.showToast(R.string.pls_input_mobile_lenght);
                } else {
                    checkMobile();
                }
                break;
            case R.id.zhuce_guanlianzhanghao:
                intent = new Intent(this, SanFangBindHxActivity.class);
                intent.putExtra("typeIDguanlian", typeID);
                intent.putExtra("tokenStr", token);
                intent.putExtra("openIdStr", openId);
                startActivityForResult(intent, 100);
                break;
            case R.id.login_close:
                finish();
                break;
            case R.id.img_inputtype:

                if (zcPassword.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
                    zcPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    img_inputtype.setImageResource(R.drawable.icon_eye_n);
                } else if (zcPassword.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {

                    zcPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    img_inputtype.setImageResource(R.drawable.icon_eye_s);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {//联系人activity返回的data
                finish();
            }
        }
    }

    //注册时的输入框非空判断
    private boolean inputZhuCeValid() {
        if (TextUtils.isEmpty(zcShouJi.getText().toString())) {
            Utils.showToast(R.string.pls_input_mobile);
            return false;
        }
        if (TextUtils.isEmpty(zcYanzhengma.getText().toString())) {
            Utils.showToast(R.string.zc_invalid_yanzheng);
            return false;
        }
        if (TextUtils.isEmpty(zcUsername.getText().toString())) {
            Utils.showToast(R.string.zc_invalid_username);
            return false;
        }
        if (TextUtils.isEmpty(zcPassword.getText().toString())) {
            Utils.showToast(R.string.zc_invalid_password);
            return false;
        }
        return true;
    }

    //注册用户名验证
    private void checkUserName() {
        String url = NetworkConstants.VALIDATE_USERNAME_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("username", zcUsername.getText().toString());
        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProfileResponse.class, false, params, new Response.Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                if (response.isSuccess()) {
                    register();
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
        //        mQueue.start();
    }


    //提交注册
    private void register() {
        String url = NetworkConstants.USER_REGISTER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", zcShouJi.getText().toString());
        params.put("captcha", zcYanzhengma.getText().toString());
        params.put("username", zcUsername.getText().toString());
        params.put("password", zcPassword.getText().toString());
        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProfileResponse.class, false, params, new Response.Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast("注册成功");
                    UmenEvent.UmengEventMap(instance, UmenEvent.APP_ACCOUNT_REGISTER, UmenEvent.ACCOUNT_REGISTER);
                    if ("sanfangguanlian".equals(intentStr)) {
                        zuceBind(zcUsername.getText().toString(), zcPassword.getText().toString());
                    } else {
                        Intent intent = new Intent(Constants.INTENT_USER_LOGGED_IN);
                        Gson gson = new Gson();
                        String json = gson.toJson(response.data);
                        intent.putExtra("loginJson", json);
                        LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                    }

                    finish();
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
        //        mQueue.start();
    }

    //注册成功后绑定刚刚注册的虎嗅账号
    private void zuceBind(String username, String password) {
        String url = NetworkConstants.USER_BINDING_URL;
        Map<String, String> params = new LinkedHashMap<>();
        switch (typeID) {
            case 1:
                params.put("oauth_type", "qq");
                break;
            case 2:
                params.put("oauth_type", "sina");
                break;
            case 3:
                params.put("oauth_type", "weixin");
                break;
        }
        params.put("oauth_uid", openId);
        params.put("oauth_token", token);
        params.put("username", zcUsername.getText().toString());
        params.put("password", zcPassword.getText().toString());
        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProfileResponse.class, false, params, new Response.Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast("绑定成功");
                    Intent intent = new Intent(Constants.INTENT_USER_LOGGED_IN);
                    Gson gson = new Gson();
                    String json = gson.toJson(response.data);
                    intent.putExtra("loginJson", json);
                    LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                    finish();
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
    }

    //检测手机号是否已经注册
    private void checkMobile() {
        String url = NetworkConstants.VALIDATE_MOBILE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", zcShouJi.getText().toString());
        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProfileResponse.class, false, params, new Response.Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                if (response.isSuccess()) {
                    getVerifyCode();
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
        //        mQueue.start();

    }

    //注册获取验证码接口
    private void getVerifyCode() {
        handler.sendEmptyMessage(MSG_COUNT_DOWN_BEGIN);
        String url = NetworkConstants.GET_SMS_CAPTCHA_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", zcShouJi.getText().toString());
        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProfileResponse.class, false, params, new Response.Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast("验证码已发送");
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
        //        mQueue.start();
    }


    //下面是登录相关接口
    private boolean inputValid() {
        if (TextUtils.isEmpty(usernameEdit.getText().toString())) {
            Utils.showToast(R.string.invalid_username);
            return false;
        }
        if (TextUtils.isEmpty(passwordEdit.getText().toString())) {
            Utils.showToast(R.string.invalid_password);
            return false;
        }
        return true;
    }


    //登录网络接口
    protected void logIn(){
        String url = NetworkConstants.USER_LOGIN_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("username", usernameEdit.getText().toString());
        params.put("password", passwordEdit.getText().toString());
        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProfileResponse.class, false, params, new Response.Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast("登录成功");
                    Intent intent = new Intent(Constants.INTENT_USER_LOGGED_IN);
                    Gson gson = new Gson();
                    String json = gson.toJson(response.data);
                    Settings.saveProfile(response.data.toString());//
                    Global.setUser(json); //保存登录信息
                    //                    Settings.saveQQToken();
                    intent.putExtra("loginJson", json);
                    LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                    finish();
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
        //        mQueue.start();
    }


    private static final int MSG_COUNT_DOWN = 30;
    private static final int MSG_COUNT_DOWN_BEGIN = 31;
    private static final int MSG_COUNT_DOWN_FINISHED = 32;
    private static final int VERIFY_CODE_TIMEOUT = 60;
    private int countDown = VERIFY_CODE_TIMEOUT;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_COUNT_DOWN_BEGIN:
                    zcFaSong.setEnabled(false);
                    sendEmptyMessage(MSG_COUNT_DOWN);
                    break;
                case MSG_COUNT_DOWN:
                    countDown--;
                    zcFaSong.setText(countDown + "秒");
                    if (countDown > 0) {
                        sendEmptyMessageDelayed(MSG_COUNT_DOWN, 1000);
                    } else {
                        zcFaSong.setText(R.string.get_verify_code_again);
                        zcFaSong.setEnabled(true);
                        sendEmptyMessage(MSG_COUNT_DOWN_FINISHED);
                    }
                    break;
                case MSG_COUNT_DOWN_FINISHED:
                    removeMessages(MSG_COUNT_DOWN);
                    if (TextUtils.isEmpty(zcYanzhengma.getText().toString())) {
                        zcFaSong.setText(R.string.get_verify_code_again);
                        zcFaSong.setEnabled(true);
                    }
                    countDown = VERIFY_CODE_TIMEOUT;
                    break;
            }
        }
    };



    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }

}
